from flask import g, Blueprint, request, jsonify, render_template, session, redirect

from common import Result
from models import Classes, TestPaper, TestPaperAnswer, QuestionAnswer, SingleChoiceQuestion, JudgmentalQuestion, \
    ShortAnswerQuestion, BaseQuestion
from exts import db, get_time
from sqlalchemy import and_
from flask_login import login_required
from decorations import student_required

bp = Blueprint("student", __name__, url_prefix="/student")


# todo before_request
@bp.before_request
@login_required
@student_required
def before_request():
    pass


# todo /jump 题目跳转
@bp.route("/jump", methods=["POST"])
def jump():
    index = request.values.get("index")
    session["all_question_count"] = int(index)
    # session.get("all_question_count")

    return "success"


# todo /query_test_paper
@bp.route("/query_test_paper", methods=["POST", "GET"])
def query_test_paper():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_class = session.get("id_class")
    state = request.values.get("state")

    classes = db.session.query(Classes).filter(Classes.id == id_class).first()
    # teacher = classes.teacher
    paginate = db.session.query(TestPaper).filter(
        and_(
            TestPaper.is_delete == 0,
            TestPaper.id_classes == id_class,
            TestPaper.state == state
        )
    ).paginate(page=int(page), per_page=int(limit))
    count = len(db.session.query(TestPaper).filter(
        and_(
            TestPaper.is_delete == 0,
            TestPaper.id_classes == id_class,
            TestPaper.state == state
        )
    ).all())
    # test_paper = classes.teacher.test_paper
    data = {
        "code": 0,
        "msg": "",
        "count": count,
        "data": []
    }
    for i in paginate.items:
        if i.state == 0:
            continue
        elif i.state == 1:
            test_paper_answer = db.session.query(TestPaperAnswer).filter(
                and_(TestPaperAnswer.id_student == g.user.student.id,
                     TestPaperAnswer.id_test_paper == i.id)).first()
            if test_paper_answer is None:
                state = "未答题"
            else:
                state = "已答题"
        else:
            state = "已收卷"

        data["data"].append({
            "id": i.id,
            "name": i.name,
            "state": state,
            "author": classes.teacher.name,
            "create_time": i.create_time
        })

    # print(data)
    return jsonify(data)


# todo /get_question
@bp.route("/get_question")
def get_question():
    id_test_paper = session.get("id_test_paper")
    test_paper = db.session.query(TestPaper).get(id_test_paper)

    question = []
    count = 0
    single_choice_question = []
    judgmental_question = []
    short_answer_question = []
    for i in test_paper.base_question:
        count += 1
        if i.question_type == 0:
            single_choice_question.append({
                "count": count,
                "type": 0,
                "question": i.single_choice_question.question,
                "a": i.single_choice_question.a,
                "b": i.single_choice_question.b,
                "c": i.single_choice_question.c,
                "d": i.single_choice_question.d,
                "id_question": i.id
            })
        elif i.question_type == 1:
            judgmental_question.append({
                "count": count,
                "type": 1,
                "question": i.judgmental_question.question,
                "id_question": i.id
            })
        else:
            short_answer_question.append({
                "count": count,
                "type": 2,
                "question": i.short_answer_question.question,
                "id_question": i.id
            })

    count = 0
    for i in single_choice_question:
        count += 1
        i["count"] = count
        question.append(i)
    for i in judgmental_question:
        count += 1
        i["count"] = count
        question.append(i)
    for i in short_answer_question:
        count += 1
        i["count"] = count
        question.append(i)

    return jsonify(question)


# todo /answer 提交答案接口
@bp.route("/answer", methods=["POST", "GET"])
def answer():
    question_type = request.form.get("question_type")
    my_answer = request.form.get("my_answer")
    print(question_type, my_answer)
    # print(question_type)
    if int(question_type) == 3:
        list_ = list(my_answer.split("&"))
        my_answer = ""
        choice = ["a", "b", "c", "d"]
        for i in range(len(choice)):
            if list_[i] == "true":
                my_answer += choice[i] + '&'
        my_answer = my_answer[:-1]

    question_id = request.values.get("question_id")

    id_test_paper = session.get("id_test_paper")

    # print(question_id, my_answer, id_test_paper)

    # 判断对错
    base_question = db.session.query(BaseQuestion).get(question_id)
    if base_question.question_type == 0:
        true_or_false = 1 if base_question.single_choice_question.answer == my_answer else 0
    elif base_question.question_type == 1:
        true_or_false = 1 if int(base_question.judgmental_question.answer) == int(my_answer) else 0
    elif base_question.question_type == 2:
        true_or_false = 1 if base_question.short_answer_question.answer == my_answer else 0
    elif base_question.question_type == 3:
        true_or_false = 1 if base_question.multiple_choice_question.answer == my_answer else 0
        # print(true_or_false)
    elif base_question.question_type == 4:
        true_or_false = 1 if base_question.picture_question.answer == my_answer else 0

    # 查看学生是否已经作答过
    test_paper_answer = db.session.query(TestPaperAnswer).filter(and_(TestPaperAnswer.id_student == g.user.student.id,
                                                                      TestPaperAnswer.id_test_paper == id_test_paper)).first()

    if test_paper_answer is None:
        test_paper_answer = TestPaperAnswer(
            score=0,
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0,
            test_paper=db.session.query(TestPaper).filter(TestPaper.id == id_test_paper).first(),
            student=g.user.student
        )

    # 查看这道题该学生是否作答过
    question_answer = db.session.query(QuestionAnswer).filter(
        and_(QuestionAnswer.id_test_paper_answer == test_paper_answer.id,
             QuestionAnswer.id_base_question == base_question.id)).first()
    if question_answer is None:
        question_answer = QuestionAnswer(
            my_answer=my_answer,
            true_or_false=true_or_false,
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0,
            test_paper_answer=test_paper_answer,
            base_question=base_question
        )
    else:
        question_answer.my_answer = my_answer,
        question_answer.update_time = get_time()

    db.session.add(question_answer)
    db.session.commit()

    session["all_question_count"] = session.get("all_question_count") + 1
    if session.get("len_all_question") == session.get("all_question_count"):
        session["all_question_count"] = session.get("all_question_count") - 1
        return "end"
    else:
        return "success"


# todo /submit_papers 交卷
@bp.route("/submit_papers", methods=["GET"])
def submit_papers():
    id_test_paper = session.get("id_test_paper")
    test_paper_answer = db.session.query(TestPaperAnswer).filter(
        and_(TestPaperAnswer.id_student == g.user.student.id, TestPaperAnswer.id_test_paper == id_test_paper)).first()
    question_answer_s = db.session.query(QuestionAnswer).filter(
        QuestionAnswer.id_test_paper_answer == test_paper_answer.id).all()
    true_count = 0
    for question_answer in question_answer_s:
        if question_answer.true_or_false == 1:
            true_count += 1

    # print(str(true_count/len(question_answer_s)))
    test_paper_answer.score = str(100 * true_count / len(question_answer_s))

    db.session.commit()

    r = Result()
    return r.success(msg="success")


# todo url /user
@bp.route("/user")
def user():
    content = {
        "user": g.user,
    }
    return render_template("student/user.html", **content)


# todo url /my_class
@bp.route("/my_class")
def my_class():
    class_id = request.values.get("class_id")
    session["id_class"] = class_id

    classes = db.session.query(Classes).get(class_id)
    content = {
        "user": g.user,
        "classes": classes
    }
    return render_template("student/my_classes.html", **content)


# todo url /test_paper_list
@bp.route("/test_paper_list")
def test_paper_list():
    session["all_question_count"] = None
    session["answer_list"] = str({})  # 记录学术的答题记录

    content = {
        "user": g.user,
        "classes": db.session.query(Classes).get(session.get("id_class"))
    }
    return render_template("student/test_paper_list.html", **content)


# todo url /test_paper_list_2
@bp.route("/test_paper_list_2")
def test_paper_list_2():
    content = {
        "user": g.user,
        "classes": db.session.query(Classes).get(session.get("id_class"))
    }
    return render_template("student/test_paper_list_2.html", **content)


# todo url /answer_sheet_url 考试详情
@bp.route("/answer_sheet_url")
def answer_sheet_url():
    id_test_paper = request.values.get("id_test_paper")

    # 判断学生是否具有答题权限（是否已经交卷）
    # tpa = db.session.query(TestPaperAnswer).filter(and_(
    #     TestPaperAnswer.id_test_paper == id_test_paper,
    #     TestPaperAnswer.id_student == g.user.student.id
    # )).first()
    # # print(tpa)
    # if tpa is not None and tpa.status == 1:
    #     return "试卷已交卷"

    session["id_test_paper"] = id_test_paper  # 记录当前的试卷id
    # session["answer_list"] = str({})  # 记录学术的答题记录

    test_paper = db.session.query(TestPaper).get(id_test_paper)
    # print(test_paper.base_question)

    single_choice_question = []
    judgmental_question = []
    short_answer_question = []
    multiple_choice_question = []
    picture_question = []
    for i in test_paper.base_question:
        if i.question_type == 0:
            single_choice_question.append({
                "type": 0,
                "question": i.single_choice_question.question,
                "a": i.single_choice_question.a,
                "b": i.single_choice_question.b,
                "c": i.single_choice_question.c,
                "d": i.single_choice_question.d,
                "id_question": i.id
            })
        elif i.question_type == 1:
            judgmental_question.append({
                "type": 1,
                "question": i.judgmental_question.question,
                "id_question": i.id
            })
        elif i.question_type == 2:
            short_answer_question.append({
                "type": 2,
                "question": i.short_answer_question.question,
                "id_question": i.id
            })
        elif i.question_type == 3:
            multiple_choice_question.append({
                "type": 3,
                "question": i.multiple_choice_question.question,
                "a": i.multiple_choice_question.a,
                "b": i.multiple_choice_question.b,
                "c": i.multiple_choice_question.c,
                "d": i.multiple_choice_question.d,
                "id_question": i.id
            })
        elif i.question_type == 4:
            picture_question.append({
                "type": 4,
                "question": i.picture_question.question,
                "id_question": i.id
            })

    all_question = []
    count = 0
    for i in single_choice_question:
        count += 1
        i["count"] = count
        all_question.append(i)
    for i in judgmental_question:
        count += 1
        i["count"] = count
        all_question.append(i)
    for i in short_answer_question:
        count += 1
        i["count"] = count
        all_question.append(i)
    for i in multiple_choice_question:
        count += 1
        i["count"] = count
        all_question.append(i)
    for i in picture_question:
        count += 1
        i["count"] = count
        all_question.append(i)

    if session.get("all_question_count") is None or session.get("all_question_count") >= len(all_question):
        session["all_question_count"] = 0
    all_question_count = session.get("all_question_count")

    session["len_all_question"] = len(all_question)

    # print(all_question_count)
    # if all_question_count == len(all_question):

    # print(all_question)
    content = {
        "user": g.user,
        "percentage": f"{all_question_count + 1}/{len(all_question)}",
        "all_question_count": all_question_count,
        "all_question": all_question,
        'single_choice_question': single_choice_question,
        'judgmental_question': judgmental_question,
        'short_answer_question': short_answer_question,
        'multiple_choice_question': multiple_choice_question,
        'picture_question': picture_question,
        "answer_list": eval(session["answer_list"])
    }
    return render_template("student/answer_sheet_url.html", **content)


# todo /test_paper_result 学生自己查看考试结果
@bp.route("/test_paper_result")
def test_paper_result():
    id_test_paper = request.values.get("id_test_paper")
    test_paper_answer = db.session.query(TestPaperAnswer).filter(and_(TestPaperAnswer.id_test_paper == id_test_paper,
                                                                      TestPaperAnswer.id_student == g.user.student.id)).first()

    single_choice_answer = []
    judgmental_answer = []
    short_answer_answer = []
    multiple_choice_question = []
    picture_question = []
    count = 0
    correct_count = 0
    for i in test_paper_answer.question_answer:
        count += 1
        if i.true_or_false == 1:
            correct_count += 1
        if i.base_question.question_type == 0:
            question = i.base_question.single_choice_question
            single_choice_answer.append({
                "count": count,
                "question": question.question,
                "a": question.a,
                "b": question.b,
                "c": question.c,
                "d": question.d,
                "answer": question.answer,
                "my_answer": i.my_answer,
                "true_or_false": '正确' if i.true_or_false == 1 else "错误"
            })
        elif i.base_question.question_type == 1:
            question = i.base_question.judgmental_question
            judgmental_answer.append({
                "count": count,
                "question": question.question,
                "answer": question.answer,
                "my_answer": i.my_answer,
                "true_or_false": '正确' if i.true_or_false == 1 else "错误"
            })
        elif i.base_question.question_type == 2:
            question = i.base_question.short_answer_question
            short_answer_answer.append({
                "count": count,
                "question": question.question,
                "answer": question.answer,
                "my_answer": i.my_answer,
                "true_or_false": '正确' if i.true_or_false == 1 else "错误"
            })
        elif i.base_question.question_type == 3:
            question = i.base_question.multiple_choice_question
            multiple_choice_question.append({
                "count": count,
                "question": question.question,
                "a": question.a,
                "b": question.b,
                "c": question.c,
                "d": question.d,
                "answer": question.answer,
                "my_answer": i.my_answer,
                "true_or_false": '正确' if i.true_or_false == 1 else "错误"
            })
        elif i.base_question.question_type == 4:
            question = i.base_question.picture_question
            picture_question.append({
                "count": count,
                "question": question.question,
                "answer": question.answer,
                "my_answer": i.my_answer,
                "true_or_false": '正确' if i.true_or_false == 1 else "错误"
            })

    content = {
        "user": g.user,
        "single_choice_answer": single_choice_answer,
        "judgmental_answer": judgmental_answer,
        "short_answer_answer": short_answer_answer,
        "multiple_choice_question": multiple_choice_question,
        "picture_question": picture_question,
        "score": test_paper_answer.score
    }
    return render_template("student/test_paper_result.html", **content)
